package com.lee.security.provider.social.impl;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Maps;
import com.lee.security.provider.social.SocialTokenCheck;
import jodd.http.HttpRequest;
import jodd.http.HttpResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.task.TaskExecutor;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Future;

/**
 * @author lee
 * @date 2018年11月22日
 */
@Component
public class WeiboTokenCheck implements SocialTokenCheck {

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private TaskExecutor myTaskExecutor;

    private static final String url = "https://api.weibo.com/oauth2/get_token_info";

    @Override
    public Future<Boolean> tokenCheck(String openId, String socialToken) {
        return CompletableFuture.supplyAsync(() -> {
            Map<String, Object> params = Maps.newLinkedHashMap();
            params.put("access_token", socialToken);
            HttpRequest httpRequest = HttpRequest.post(url).form(params).acceptEncoding("UTF-8");
            HttpResponse httpResponse = httpRequest.send();
            String body = httpResponse.bodyText();
            JsonNode readNode;
            try {
                readNode = objectMapper.readTree(body);
            } catch (IOException e) {
                return false;
            }
            String uid = readNode.path("uid").asText();
            return StringUtils.equals(uid, openId);
        }, myTaskExecutor).exceptionally(e -> false);
    }

}
